package b1.mobile.blackberry.util;

import java.util.Vector;

import net.rim.device.api.ui.Font;
import b1.mobile.blackberry.ui.component.util.FontFactory;

public class StringUtil {
	public static Vector parseMessage(String text, Font fnt, int width) {

		Vector result = new Vector ();
		  
	    String remaining = text;
	    
	    while (remaining.length()>=0)
	    {
	    	int index = getSplitIndex(remaining, width);
	    	
	    	if (index == -1)
	    		break;
	    	
	    	result.addElement(remaining.substring(0,index));
	    	
	    	remaining = remaining.substring(index);
	    	
	    	if (index == 0)
	    		break;
	    }
	    
	    String last = (String) result.elementAt(result.size()-1);
	    if (last.trim().length()<1){
	    	result.removeElementAt(result.size()-1);
	    }
	    return result;
	}
	
	private static int getSplitIndex(String bigString, int width)
	{
		int index = -1;
		int lastSpace = -1;
		String smallString="";
		boolean spaceEncountered = false;
		boolean maxWidthFound = false;
		
		for (int i=0; i<bigString.length(); i++)
		{
			char current = bigString.charAt(i);
			smallString += current;
			
			
			if (current == ' ')
			{
				lastSpace = i;
				spaceEncountered = true;
			}
			
			int linewidth =	FontFactory.getFont(Font.PLAIN, 6).getAdvance(smallString,0,  smallString.length());
			
			if(linewidth>width)
			{
				if (spaceEncountered)
					index = lastSpace+1;
				else
					index = i;
				
				maxWidthFound = true;
				
				break;
				
				
			}
			
			
		}
		
		if (!maxWidthFound)
			index = bigString.length();
		
		
		return index;
	}
	
	public static String[] parseKPITable(Object[] orgData){
		
		Vector dataVector = new Vector();
		
		String[] leftString = (String[]) orgData[0];
		String[] rightString = (String[])orgData[1];
		
		for (int i=0; i<leftString.length; i++){
			dataVector.addElement(leftString[i]);
			dataVector.addElement(rightString[i]);
		}
		String[] data = new String[dataVector.size()];
		dataVector.copyInto(data);
		
		return data;
	}
}
